<?php
/**
 * NOTICE OF LICENSE
 *
 * This source file is subject to the  Academic Free License (AFL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to support@zprofess.com so we can send you a copy immediately.
 *
 * @category   	Prestashop module
 * @package		Customer Point
 * @version 	1.0 (March 2012)
 * @author 		kurosaki <kurosaki@zprofess.com>
 * @copyright   Copyright (c) 2011 ZPROFESS. (http://www.zprofess.com)
 * @license    	http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

if (!defined('_CAN_LOAD_FILES_'))
    exit;
    
require_once(_PS_MODULE_DIR_.'zcustomerpoint/classes/ZCustomerPointConfig.php');
require_once(_PS_MODULE_DIR_.'zcustomerpoint/classes/ZcustomerPointObject.php');
    
final class ZCustomerPoint extends ZCustomerPointConfig
{
	
	const INSTALL_SQL_FILE = 'sql/install.sql';
	const UNINSTALL_SQL_FILE = 'sql/uninstall.sql';
	 /**
     * Sole constructor
     */
	public function __construct()
	{
		$this->name = 'zcustomerpoint';	
		$this->version = '1.0.0';
		$this->author = 'Zprofess.com';
		$this->confirmUninstall = $this->l('Bạn có chắc muốn gỡ module không ?');
		$this->displayName = $this->l('Customer Point');
		$this->description = $this->l('Mô tả Point');
		
		parent::__construct();
	}
	
	 /**
     * Intall module. Creates module tables and adds module configuration
     * to configuration table.
     * @return boolean true if this module installs successfully, false
     * otherwise
     */
    public function install() {
    	if (!parent::install())
			return false;
			
        /*Register Hook*/
		if (!$this->registerHook('header')
		 OR !$this->registerHook('createAccount')
		 OR !$this->registerHook('adminCustomers')
		 OR !$this->registerHook('authentication')
		 OR !$this->registerHook('footer'))
			return false;
		
		if (!$this->_addAdminTab(array('parentClassName' 	=> 'AdminCustomers',
									   'childClassName' 	=> 'ZadminCustomerPoint',
									   'childTabName' 		=> 'Point ')))
			return false;
		/* install SQL file */
		if (!$this->_sql(self::INSTALL_SQL_FILE))
			return false;
			
        /*
		if (!$this->initConfiguration())
        	return false;
        */	
        
        return true;
    }

    /**
     * Uninstall module.
     * Drops module tables from the DB and removes module configuration from
     * the configuration table.
     * @return boolean true if this module uninstalls successfully, false
     * otherwise
     */
	public function uninstall()
	{
		if (!parent::uninstall())
			return false;
			
		if (!$this->_sql(self::UNINSTALL_SQL_FILE))
			return false;
		
		if (!$this->_removeAdminTab('ZadminCustomerPoint'))
			return false;
		/*
		if (!$this->destroyConfiguration())
			return false;
		*/
			
		return true;
	}
	
	
	function hookHeader($params)
	{
//		Tools::addJS($this->_path.'js/add-parent-customer.js');
	}
	
	function hookCreateAccount ($params)
	{
		global $currency, $smarty, $cookie;
		if (Tools::isSubmit('submitAccount') OR Tools::isSubmit('submitGuestAccount')){
			/* get id parent customer of new account */
			$id_customer_parent = DB::getInstance()->getRow('SELECT id_customer FROM '._DB_PREFIX_.'customer WHERE username="'.$_POST['parent'].'"');
			$pointsReg = Configuration::get('ZPOINTS_REG');
			$pointsParent = Configuration::get('ZPOINTS_PARENT');
			/* add points to customer when registering */
			ZcustomerPointObject::_addPointRegistering((int)$id_customer_parent['id_customer'], $pointsReg, $_POST['name'], $_POST['username']);
			/* update point to parent customer */
			if ($id_customer_parent)
				ZcustomerPointObject::_updatePointToCustomer((int)$id_customer_parent['id_customer'], $pointsParent);
		}
	}
	
	function hookAdminCustomers ($params){
		global $cookie, $smarty, $currentIndex;
		/* get array customer point */
		$customerPoint = Db::getInstance()->getRow('SELECT * FROM '._DB_PREFIX_.'zcustomerpoint_accounts 
														WHERE id_customer = '.Tools::getValue('id_customer'));
		/* get array parent customer point */
		if ($customerPoint['id_customer_parent'])
			$customerParent = Db::getInstance()->getRow('SELECT * FROM '._DB_PREFIX_.'customer 
														WHERE id_customer = '.$customerPoint['id_customer_parent']);
		// sub point to customer parent when add block list
		$pointsFalse = Configuration::get('ZPOINTS_FALSE');
		// add point to customer parent when remove block list
		$pointsTrue =  Configuration::get('ZPOINTS_TRUE');
		/* process bock or disBlock */
		// Block = true
		if (isset($_GET['block']) AND $_GET['block'] == 1){
			/* update status block account */
			ZcustomerPointObject::_changeBlock($_GET['block'], (int)(Tools::getValue('id_customer')));
			/* if exist parent customer, update point current */
			if ($customerPoint['id_customer_parent'])
				ZcustomerPointObject::_updatePointToCustomer((int)($customerPoint['id_customer_parent']), $pointsFalse, false);
				
			Tools::redirectAdmin($currentIndex.'&id_customer='.Tools::getValue('id_customer').'&conf=4&viewcustomer&token='.Tools::getValue('token'));	
		//Block False
		}elseif (isset($_GET['block']) AND $_GET['block'] == 0){
			/* update status block account */
			ZcustomerPointObject::_changeBlock($_GET['block'], (int)(Tools::getValue('id_customer')));
			/* if exist parent customer, update point current */
			if ($customerPoint['id_customer_parent'])
				ZcustomerPointObject::_updatePointToCustomer((int)$customerPoint['id_customer_parent'], $pointsTrue);
				
			Tools::redirectAdmin($currentIndex.'&id_customer='.Tools::getValue('id_customer').'&conf=4&viewcustomer&token='.Tools::getValue('token'));
		}
		
		/* Display table information point of account */
		$tokenAddresses = Tools::getAdminToken('ZadminCustomerPoint'.(int)(Tab::getIdFromClassName('ZadminCustomerPoint')).(int)($cookie->id_employee));
		if ($customerPoint['id_customer']){
			echo '<h2>'.$this->l('Điểm Point').' ('.$customerPoint['points_current'].')</h2>';
			
			echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th class="center">'.$this->l('Người giới thiệu').'</th>
					<th class="center" width="100px">'.$this->l('Điểm Point').'</th>
					<th class="center">'.$this->l('Block').'</th>
					<th>'.$this->l('Sửa').'</th>
				</tr>
				<tr>
					'.($customerPoint['id_customer_parent'] ? '<td>'.$customerParent['username'].'</td>' : '<td>--</td>').'
					<td align="center">'.$customerPoint['points_current'].'</td>
					<td align="center">'.($customerPoint['block'] == 1 ? '<a href="'.$currentIndex.'&id_customer='.Tools::getValue('id_customer').'&block=0&viewcustomer&token='.Tools::getValue('token').'"><img src="../img/admin/enabled.gif" /></a>' : '<a href="'.$currentIndex.'&id_customer='.Tools::getValue('id_customer').'&block=1&viewcustomer&token='.Tools::getValue('token').'"><img src="../img/admin/disabled.gif" /></a>').'</td>
					<td align="center">
						<a href="?tab=ZadminCustomerPoint&id_zcustomerpoint_accounts='.$customerPoint['id_zcustomerpoint_accounts'].'&updatezcustomerpoint_accounts&token='.$tokenAddresses.'"><img src="../img/admin/edit.gif" /></a>
					</td>
				</tr>';
			echo '</table>';
		}
	}
	
	function hookAuthentication ($params)
	{
		global $cookie;
		$time_now = date('Y-m-d H:i:s');
		$cookie->start_track_time_tmp = $time_now;
		$cookie->start_track_time = $cookie->start_track_time_tmp;
	}
	
	
	function hookFooter ($params)
	{
		global $currency, $smarty, $cookie;
		$checkLogged = $params['cookie']->isLogged();
		$time_now = date('Y-m-d H:i:s');
		$timeDelay =  Configuration::get('ZTIMES_DELAY'); //(min)
		$timesAdd = Configuration::get('ZTIMES_ADD'); //(min)
		$pointsTime = Configuration::get('ZPOINTS_TIME'); //points add 
		if(isset($checkLogged) AND $checkLogged==1){
			ZcustomerPointObject::_addPointByTimes($timeDelay, $timesAdd, $pointsTime);
		}
	}
}